﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

/// <summary>
///UserAuthorizationModule 的摘要说明
/// </summary>
public class UserAuthorizationModule : IHttpModule
{
    public void Dispose()
    {
        //throw new NotImplementedException();
    }

    public void Init(HttpApplication context)
    {
        //throw new NotImplementedException();

        context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
    }

    void context_AcquireRequestState(object sender, EventArgs e)
    {

        // 获取应用程序
        HttpApplication application = (HttpApplication)sender;
        String requestUrl = application.Request.Url.ToString();

        //WriteLog(requestUrl);
        //application.Response.Write(requestUrl);
        //WriteLog(requestUrl.IndexOf("admin").ToString());
        //WriteLog(requestUrl.IndexOf("reader").ToString());

        if (requestUrl.IndexOf("admin") != -1) //路径包含admin,需要检查是否有管理员的登录信息
        {
            if (application.Context.Session["admin"] == null
                || application.Context.Session["admin"].ToString().Trim() == "")
            {
                //没有管理员的登录信息，跳转到登录页面
                application.Session.Clear();
                application.Response.Redirect("~/login.aspx");
            }
        }
        else if (requestUrl.IndexOf("reader") != -1) //路径包含reader,需要检查是否有读者的登录信息
        {
            if (application.Context.Session["reader"] == null
                || application.Context.Session["reader"].ToString().Trim() == "")
            {
                //没有管理员的登录信息，跳转到登录页面
                application.Session.Clear();
                application.Response.Redirect("~/login.aspx");
            }
        }
        //如果路径中既不包含admin也不包含reader，则不处理
    }

    public void WriteLog(string message)
    {
        string path = @"d:\httpmodule.txt";
        StreamWriter writer = null;
        if (!File.Exists(path))
        {
            writer = File.CreateText(path);
        }
        else
        {
            FileInfo info = new FileInfo(path);
            writer = info.AppendText();

        }
        writer.WriteLine(DateTime.Now.ToLongTimeString() + ": " + message);

        writer.Flush();
        writer.Close();
    }

}